package com.kpmg.datalake.common.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class FileUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
	
	private FileUtil(){
		
	}
	
	/**
	 * 获取目录下所有excel文件
	 * @param args
	 * @throws SAXException
	 * @throws IOException
	 * @throws ParserConfigurationException
	 */
	public static List<File> getExcelFileList(String filePath,List<File> fileList) {
		File dir = new File(filePath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();
                if (files[i].isDirectory()) { // 判断是文件还是文件夹
                	getExcelFileList(files[i].getAbsolutePath(),fileList); // 获取文件绝对路径
                } else if (fileName.endsWith("xlsx")||fileName.endsWith("xls")) { // 判断文件名是否以.xlsx或.xls结尾
                    fileList.add(files[i]);
                } else {
                    continue;
                }
            }

        }
        return fileList;
    }
	
	
	
	
	/**
	 * 解析xml文件
	 * @param File file
	 * @return
	 * @throws SAXException
	 * @throws IOException
	 * @throws ParserConfigurationException
	 */
	public static List<Map<String,Object>> xmlRead(File file) {
		List<Map<String,Object>> xmlList=new ArrayList<Map<String,Object>>();
		//创建DocumentBuilderFactory对象  
        DocumentBuilderFactory a = DocumentBuilderFactory.newInstance();
        //创建DocumentBuilder对象  
        DocumentBuilder b = null; 
        //通过DocumentBuilder对象的parse方法返回一个Document对象  
        Document document = null;  
        try {
			b = a.newDocumentBuilder();
			document = b.parse(file);
			//获取根节点
			Element root=document.getDocumentElement();
			//获取根节点的所有子节点
			NodeList rootChilds=root.getChildNodes();  
			if(rootChilds.getLength()>0){
				xmlList=childRead(rootChilds);
			}
		} catch (ParserConfigurationException | SAXException | IOException e) {
			logger.debug("xml文件解析失败", e);
			xmlList=new ArrayList<Map<String,Object>>();
			Map<String,Object>map=new HashMap<String,Object>();
			map.put("isError", "1");
			map.put("exception", e);
			xmlList.add(map);
		} 
        
		return xmlList;
	}
	
	/**
	 * 判断是否还有子节点
	 * @param childLength
	 * @param child
	 */
	public static int hasChild(int childLength,Node child){
		//判断是否还有子节点
		for(int j=childLength-1;j>=0;j--){
			if(child.getChildNodes().item(j).getNodeType()!=Node.ELEMENT_NODE){
				childLength--;
			}
		}
		return childLength;
	}
	
	/**
	 * 通过递归读取xml所有子节点
	 * @param childs
	 * @return
	 */
	public static List<Map<String,Object>> childRead(NodeList childs){
		List<Map<String,Object>> childsList=new ArrayList<Map<String,Object>>();
		for(int i=0;i<childs.getLength();i++){
			Map<String,Object>childsMap=new HashMap<String,Object>();
			Node child=childs.item(i);
			//判断是否为节点
			if(child.getNodeType() == Node.ELEMENT_NODE){
				int childLength=child.getChildNodes().getLength();
				String textContent="true";
				//判断是否还有子节点
				childLength=hasChild(childLength,child);
				if(childLength>0){
					childsMap.put("childs", childRead(child.getChildNodes()));
				}else{
					//获取标签文本
					textContent=child.getTextContent().trim();
				}
				if("".equals(textContent)){
					textContent="true";
				}
				
				//获取所有属性
				NamedNodeMap attrMap=child.getAttributes();
				for(int k=0;k<attrMap.getLength();k++){
					Node attr=attrMap.item(k);
					childsMap.put(attr.getNodeName(), attr.getNodeValue());
				}
				//获取标签名
				childsMap.put(child.getNodeName(),textContent );
				childsList.add(childsMap);
			}
		}
		
		return childsList;
	}

}
